package com.py.credit.controller;

import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.DictDetailEntity;
import com.py.credit.entity.GatewayUserEntity;
import com.py.credit.entity.SysUser;
import com.py.credit.service.*;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.helper.HttpServletHelper;
import com.py.framework.core.log.ExceptionLogger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Company: WWW.xypy.com.cn
 * @ClassName UserEvaInfoController
 * @Description: 信用评价申报功能控制器
 * @Params:
 * @Author: YaoS
 * @Create: 2018-10-24 11:18
 **/
@RestController
@RequestMapping(value = "/xypj/gateway")
public class UserEvaInfoController {
    //区域常量
    private static final String ZONE = "ZONE";
    //行业代码常量
    private static final String HYDM = "HYDM";
    //报告类型常量
    private static final String BGLX = "BGLX";
    //可选报告
    private static final String KXBG = "KXBG";
    @Autowired
    private UserEvaInfoService userEvaInfoService;
    @Autowired
    private EvalInfoService evalInfoService;
    @Autowired
    private XypjRemoteBaseService xypjRemoteBaseService;
    @Autowired
    GatewayAuthenticationService gatewayAuthenticationService;
    @Autowired
    SysDictService sysDictService;

    /**
     * 模型查询接口
     *
     * @param zone
     * @param industry
     * @param reportType
     * @return RestServiceResult
     * @author YaoS
     * @date 14:17 18/10/24
     **/
    @RequestMapping(value = "/selectModel.json")
    public RestServiceResult<Map<String, Object>> selectModel(
            @RequestParam(value = "zone", defaultValue = "", required = true) String zone,
            @RequestParam(value = "industry", defaultValue = "", required = true) String industry,
            @RequestParam(value = "reportType", defaultValue = "", required = true) String reportType,
            @RequestParam(value = "orgId", defaultValue = "", required = true) String orgId,
            HttpServletRequest request) {
        RestServiceResult r = new RestServiceResult<List<DictDetailEntity>>();
        Map<String, Object> map = new HashMap<>(2);
        GatewayUserEntity user = new GatewayUserEntity();
        String token = HttpServletHelper.getUserXypjGatewayToken(request);
        try {
            user = gatewayAuthenticationService.getCurrentUserInfo(token);
        } catch (Exception e) {
            ExceptionLogger.error("UserEvaInfoController#selectModel", "未获取到当前用户信息！");
        }
        try {
            String modelId = userEvaInfoService.selectAllTable(zone, industry, reportType);
            String status = userEvaInfoService.selectStatusByModel(user.getId() + "", modelId);
            Integer count = userEvaInfoService.selectOrgAndModel(modelId, orgId);
            Integer count1 = userEvaInfoService.selectExistReport(modelId, orgId, String.valueOf(user.getId()));
            if (null != modelId && count > 0) {
                map.put("modelId", modelId);
                map.put("status", status);
                r.setData(map);
            } else if (count1 <= 0) {
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("该机构下不存在这个模型！");
            } else {
                r.setCode(RestServiceResult.CODE_UNKNOW);
                r.setMsg("此模版不存在！");
            }
            return r;
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("模版查询失败！");
            return r;
        }
    }

    /**
     * 查询所有的表
     *
     * @param
     * @return
     * @author YaoS
     * @date 12:06 18/11/3
     **/
    @IgnoreAuthority
    @RequestMapping(value = "/selectAllEvaTable.json")
    public RestServiceResult<Map<String, Object>> selectAllEvaTable(
            @RequestParam(value = "modelId", defaultValue = "", required = true) String modelId,
            @RequestParam(value = "evainfoId", defaultValue = "", required = true) String evainfoId,
            HttpServletRequest request) {
        RestServiceResult r = new RestServiceResult<List<DictDetailEntity>>();
        Map map = new HashMap();
        List list = new ArrayList();
        GatewayUserEntity user = new GatewayUserEntity();
        String token = HttpServletHelper.getUserXypjGatewayToken(request);
        try {
            user = gatewayAuthenticationService.getCurrentUserInfo(token);
        } catch (Exception e) {
            ExceptionLogger.error("UserReportController#insertIndexTable", "未获取到当前用户信息！");
        }
        try {
            list = userEvaInfoService.selectIndexOrCategroy(modelId, user.getId() + "", evainfoId);
            r.setData(list);
            return r;
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("信用评价查询失败！");
            return r;
        }
    }


    @RequestMapping(value = "/viewCheck.do")
    public RestServiceResult<List<Map>> viewCheck(
            @RequestParam(value = "modelId", defaultValue = "", required = true) String modelId,
            @RequestParam(value = "evainfoId", defaultValue = "", required = true) String evainfoId,
            HttpServletRequest request) {
        String token = HttpServletHelper.getUserXypjGatewayToken(request);
        RestServiceResult<List<Map>> result = new RestServiceResult<List<Map>>();
        // 获取当前用户信息
        RestServiceResult<SysUser> user = xypjRemoteBaseService.getCurrentUser(token);
        SysUser userInfo = null;
        if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
            userInfo = user.getData();
            if (null == userInfo || userInfo.getId() <= 0) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("系统异常，请稍后再试！");
                ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
                return result;
            }
        } else {
            result.setCode(user.getCode());
            result.setMsg(user.getMsg());
            return result;
        }
        try {
            List<Map> list = userEvaInfoService.viewCheck(modelId, String.valueOf(userInfo.getId()), evainfoId);
            result.setData(list);
            return result;
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("评价详情页面异常，请稍后再试！");
            ExceptionLogger.error("评价详情页面异常！", e.getMessage(), e);
            return result;
        }
    }

    /**
     * 诚信评价-信用申报1：获取字典表
     *
     * @param
     * @return RestServiceResult
     * @author YaoS
     * @date 14:12 18/10/24
     **/
    @RequestMapping(value = "/getEvaDictory.json")
    public RestServiceResult getEvaDictory(
            @RequestParam(value = "zone", defaultValue = "", required = true) String zone,
            @RequestParam(value = "scoreType", defaultValue = "2", required = true) String scoreType,
            @RequestParam(value = "industry", defaultValue = "", required = true) String industry) {
        RestServiceResult r = new RestServiceResult<List<DictDetailEntity>>();
        Map<String, Object> map = new HashMap<>();
        try {
            List<DictDetailEntity> zonelist = sysDictService.getDictDetails(ZONE, StringUtils.EMPTY);
            List<DictDetailEntity> hydmlist = sysDictService.getDictDetails(HYDM, StringUtils.EMPTY);
            List<DictDetailEntity> bglxlist = sysDictService.getDictDetails(BGLX, StringUtils.EMPTY);
            List kxbglist = userEvaInfoService.selectReport(zone, scoreType, industry);
            map.put(ZONE, zonelist);
            map.put(HYDM, hydmlist);
            map.put(BGLX, bglxlist);
            map.put(KXBG, kxbglist);
            r.setData(map);
            return r;
        } catch (Exception e) {
            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("字典值查询失败！" + e.getMessage());
            return r;
        }
    }


    /**
     * 插入指标入表
     *
     * @param
     * @return
     * @author YaoS
     * @date 11:47 18/10/27
     **/
    @RequestMapping(value = "/insertIndexTable.json")
    public RestServiceResult insertIndexTable(
            @RequestParam(value = "tablelist", defaultValue = "", required = true) String tablelist, String modelId, String evalinfoId, String orgId,
            HttpServletRequest request) {
        GatewayUserEntity user = new GatewayUserEntity();
        RestServiceResult result = new RestServiceResult<>();
        String token = HttpServletHelper.getUserXypjGatewayToken(request);
        try {
            user = gatewayAuthenticationService.getCurrentUserInfo(token);
        } catch (Exception e) {
            ExceptionLogger.error("UserReportController#insertIndexTable", "未获取到当前用户信息！");
        }
        List<Map<String, String>> list = JSONObject.parseObject(tablelist, List.class);
        try {
            if (!("").equals(evalinfoId) && null != evalinfoId) {
                userEvaInfoService.updateDelFlag(evalinfoId);
            }
            userEvaInfoService.insertIndexTable(list, user.getUsername(), user.getId() + "", modelId, orgId);
        } catch (Exception e) {
            result.setCode(RestServiceResult.CODE_UNKNOW);
            result.setMsg("数据入库错误！" + e.getMessage());
            return result;
        }
        return result;
    }

    /**
     * 指标上传文件
     *
     * @param indexId 统一编码
     * @param modelId 模型id
     * @return
     * @author YaoS
     * @date 15:00 18/11/5
     **/
    @RequestMapping(value = "/uploadFile.json")
    public RestServiceResult<List<Map<String, Object>>> uploadFile(
            @RequestParam(value = "indexId", defaultValue = "", required = true) String indexId,
            @RequestParam(value = "modelId", defaultValue = "", required = true) String modelId,
            @RequestParam(value = "file", defaultValue = "", required = true) MultipartFile file,
            HttpServletRequest request, HttpServletResponse response
    ) {
        RestServiceResult result = new RestServiceResult<>();
        GatewayUserEntity user = new GatewayUserEntity();
        String token = HttpServletHelper.getUserXypjGatewayToken(request);
        try {
            user = gatewayAuthenticationService.getCurrentUserInfo(token);
        } catch (Exception e) {
            ExceptionLogger.error("UserReportController#uploadFile", "未获取到当前用户信息！");
        }
        String filePath = "";
        if (!file.isEmpty()) {
            if (!file.getOriginalFilename().toLowerCase().endsWith(".zip") &&
                    !file.getOriginalFilename().toLowerCase().endsWith(".rar") &&
                    !file.getOriginalFilename().toLowerCase().endsWith(".7z")) {
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("文件类型不对!,只允许压缩文件！");
                return result;
            }
            //拼接文件存储路径
            filePath = user.getDirPath() + File.separator + "modelFile" + File.separator + modelId + File.separator + indexId;
            try {
                //删除原先文件夹
                FileUtils.deleteDirectory(new File(filePath));
                userEvaInfoService.fileUpload(file, filePath);
                filePath = filePath + File.separator + file.getOriginalFilename();
            } catch (IOException e) {
                ExceptionLogger.error(e);
                result.setCode(RestServiceResult.CODE_UNKNOW);
                result.setMsg("上传" + file.getOriginalFilename() + "文件类型失败!");
                return result;
            }
            result.setData(filePath);
        }
        return result;
    }


    @RequestMapping(value = "/fileDownload.json")
    public void fileDownload(
            @RequestParam(value = "path", defaultValue = "", required = true) String path,
            HttpServletRequest request, HttpServletResponse response
    ) {
        userEvaInfoService.fileDownload(path, request, response);
    }

    @RequestMapping("/selectModelList.json")
    public RestServiceResult<List<Map<String, String>>> selectModelList(String orgName) {
        RestServiceResult<List<Map<String, String>>> r = new RestServiceResult<>();
        try {
            r.setData(evalInfoService.selectModelList(orgName));
        } catch (Exception e) {

            r.setCode(RestServiceResult.CODE_UNKNOW);
            r.setMsg("模型名称查询失败！");
        }

        return r;
    }
}
